package com.itcaius.weblog.admin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcaius.weblog.admin.model.vo.tag.*;
import com.itcaius.weblog.admin.service.AdminTagService;
import com.itcaius.weblog.common.domain.dos.ArticleTagRelDO;
import com.itcaius.weblog.common.domain.dos.TagDO;
import com.itcaius.weblog.common.domain.mapper.ArticleTagRelMapper;
import com.itcaius.weblog.common.domain.mapper.TagMapper;
import com.itcaius.weblog.common.enums.ResponseCodeEnum;
import com.itcaius.weblog.common.exception.BizException;
import com.itcaius.weblog.common.model.vo.SelectRspVO;
import com.itcaius.weblog.common.utils.PageResponse;
import com.itcaius.weblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Caius
 * @description
 * @since Created in 2025-04-25
 */
@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements AdminTagService {

    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private ArticleTagRelMapper articleTagRelMapper;

    @Override
    public Response addTags(AddTagReqVO addTagReqVO) {
        // vo 转 do
        List<TagDO> tagDOS = addTagReqVO.getTags()
                .stream().map(tagName -> TagDO.builder()
                        .name(tagName.trim())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build())
                .collect(Collectors.toList());

        try {
            saveBatch(tagDOS);
        } catch (Exception e){
            log.warn("该标签已存在", e);
        }

        return Response.success();
    }

    @Override
    public PageResponse findTagPageList(FindTagPageListReqVO findTagPageListReqVO) {
        // 分页参数，请求参数
        Long current = findTagPageListReqVO.getCurrentPage();
        Long size = findTagPageListReqVO.getSize();

        String name = findTagPageListReqVO.getName();
        LocalDate startTime = findTagPageListReqVO.getStartTime();
        LocalDate endTime = findTagPageListReqVO.getEndTime();

        Page<TagDO> page = tagMapper.selectPageList(current, size, name, startTime, endTime);

        List<TagDO> tagDOS = page.getRecords();

        // do 转 vo
        List<FindTagPageListRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOS)) {
            vos = tagDOS.stream()
                    .map(tagDO -> FindTagPageListRspVO.builder()
                            .id(tagDO.getId())
                            .name(tagDO.getName())
                            .createTime(tagDO.getCreateTime())
                            .articlesTotal(tagDO.getArticlesTotal())
                            .build())
                    .collect(Collectors.toList());
        }

        return PageResponse.success(page, vos);
    }

    @Override
    public Response deleteTag(DeleteTagReqVO deleteTagReqVO) {
        Long deleteTagReqVOId = deleteTagReqVO.getId();

        // 校验该标签下面是否存在文章
        ArticleTagRelDO tagRelDO = articleTagRelMapper.selectOneByTagId(deleteTagReqVOId);

        if (Objects.nonNull(tagRelDO)) {
            log.warn("==> 此标签下包含文章，无法删除， tagId: {}", deleteTagReqVOId);
            throw new BizException(ResponseCodeEnum.TAG_CAN_NOT_DELETE);
        }

        // 根据标签 id 进行删除
        int count = tagMapper.deleteById(deleteTagReqVOId);

        return count == 1 ? Response.success() : Response.fail(ResponseCodeEnum.TAG_NOT_EXISTED);
    }

    @Override
    public Response searchTag(SearchTagReqVO searchTagReqVO) {
        String key = searchTagReqVO.getKey();

        List<TagDO> tagDOS = tagMapper.selectByKey(key);

        List<SelectRspVO> vos = null;

        if (!CollectionUtils.isEmpty(tagDOS)) {
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }

        return Response.success(vos);
    }


    @Override
    public Response findTagSelectList() {

        List<TagDO> tagDOS = tagMapper.selectList(Wrappers.emptyWrapper());

        List<SelectRspVO> vos = null;

        if (!CollectionUtils.isEmpty(tagDOS)) {
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }
        return Response.success(vos);
    }
}
